package com.fh.controller.system.weixin;

import com.fh.controller.base.BaseController;
import com.fh.controller.system.weixin.resp.AccessToken;
import com.fh.controller.system.weixin.wxutil.WeixinUtil;
import com.fh.service.building.bill.BillService;
import com.fh.service.contract.cuser.CUserService;
import com.fh.service.weixin.WeixinService;
import com.fh.util.*;
import net.sf.json.JSONObject;
import org.jsoup.helper.DataUtil;
import org.marker.weixin.DefaultSession;
import org.marker.weixin.HandleMessageAdapter;
import org.marker.weixin.MySecurity;
import org.marker.weixin.msg.*;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 *
* 类名称：WeixinController.java
* 类描述： 微信公共平台开发
* @author caozengling
* 作者单位：
* 联系方式：
* 创建时间：2018年3月21日 8:53:38
* @version 1.0
 */

@Controller
@RequestMapping(value="/weixin")
public class WeixinController extends BaseController{
	@Autowired
	private CUserService cUserService;
	@Autowired
	private WeixinService weixinService;
@Autowired
private BillService billService;
	/**
	 * 接口验证,总入口
	 * @param out
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	 @RequestMapping(value="/index")
	 public void index(
			 PrintWriter out,
			 HttpServletRequest request,
			 HttpServletResponse response
			 ) throws Exception{
		 logBefore(logger, "微信接口");
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			String signature = pd.getString("signature");		//微信加密签名
			String timestamp = pd.getString("timestamp");		//时间戳
			String nonce	 = pd.getString("nonce");			//随机数
			String echostr 	 = pd.getString("echostr");			//字符串

			if(null != signature && null != timestamp && null != nonce && null != echostr){
/* 接口验证  */

				System.out.println("========进入身份验证");
			    List<String> list = new ArrayList<String>(3) {
				    private static final long serialVersionUID = 2621444383666420433L;
				    public String toString() {  // 重写toString方法，得到三个参数的拼接字符串
				               return this.get(0) + this.get(1) + this.get(2);
				           }
				         };
				   list.add(Tools.readTxtFile(Const.WEIXIN)); 		//读取Token(令牌)
				   list.add(timestamp);
				   list.add(nonce);
				   Collections.sort(list);							// 排序
				   String tmpStr = new MySecurity().encode(list.toString(),
				    MySecurity.SHA_1);								// SHA-1加密

				    if (signature.equals(tmpStr)) {
				           out.write(echostr);						// 请求验证成功，返回随机码
				     }else{
				           out.write("");
			       }
				out.flush();
				out.close();
			}else{
/* 消息处理  */

				System.out.println("========进入消息处理");
				response.reset();
				sendMsg(request,response);
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

/**
	  * 处理微信服务器发过来的各种消息，包括：文本、图片、地理位置、音乐等等
	  * @param request
	  * @param response
	  * @throws Exception
	  */

public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws Exception{

	InputStream is = request.getInputStream();
	OutputStream os = response.getOutputStream();

	final DefaultSession session = DefaultSession.newInstance();
	session.addOnHandleMessageListener(new HandleMessageAdapter(){

		/**
		 * 事件
		 */
		@Override
		public void onEventMsg(Msg4Event msg) {
			/** msg.getEvent()
			 * unsubscribe：取消关注 ; subscribe：关注
			 */
			if("subscribe".equals(msg.getEvent())){
				returnMSg(msg,null,"关注");
			}else if("CLICK".equals(msg.getEvent())){
				returnMSg(msg,null,msg.getEventKey());
			}else if("VIEW".equals(msg.getEvent())){
				System.out.println(msg);
//				OAuthUtil.getOauth2AccessToken("wxb7f6c9100ba0a6cc","e8dcbbde25f54500058a6687324e3e3b","code");
				System.out.println("转向一个网页");
			}
		}

		/**
		 * 收到的文本消息
		 */
		@Override
		public void onTextMsg(Msg4Text msg) {
			returnMSg(null,msg,msg.getContent().trim());
		}

		@Override
		public void onImageMsg(Msg4Image msg) {
			// TODO Auto-generated method stub
			super.onImageMsg(msg);
		}

		@Override
		public void onLocationMsg(Msg4Location msg) {
			// TODO Auto-generated method stub
			super.onLocationMsg(msg);
		}

		@Override
		public void onLinkMsg(Msg4Link msg) {
			// TODO Auto-generated method stub
			super.onLinkMsg(msg);
		}

		@Override
		public void onVideoMsg(Msg4Video msg) {
			// TODO Auto-generated method stub
			super.onVideoMsg(msg);
		}

		@Override
		public void onVoiceMsg(Msg4Voice msg) {
			// TODO Auto-generated method stub
			super.onVoiceMsg(msg);
		}

		@Override
		public void onErrorMsg(int errorCode) {
			// TODO Auto-generated method stub
			super.onErrorMsg(errorCode);
		}

		/**
		 * 返回消息
		 * @param emsg
		 * @param tmsg
		 * @param getmsg
		 */
		public void returnMSg(Msg4Event emsg, Msg4Text tmsg, String getmsg){
			PageData msgpd;
			PageData pd = new PageData();
			String toUserName,fromUserName,createTime;
			if(null == emsg){
				toUserName = tmsg.getToUserName();
				fromUserName = tmsg.getFromUserName();
				createTime = tmsg.getCreateTime();
			}else{
				toUserName = emsg.getToUserName();
				fromUserName = emsg.getFromUserName();
				createTime = emsg.getCreateTime();
			}
			pd.put("KEYWORD", getmsg);
			try {
//				msgpd = textmsgService.findByKw(pd);
				if("1".equals(tmsg.getContent())){
					Msg4Text rmsg = new Msg4Text();
					rmsg.setFromUserName(toUserName);
					//System.out.println(toUserName + "====" + fromUserName);
					//fromUserName  关注者的身份ID
					rmsg.setToUserName(fromUserName);
					//rmsg.setFuncFlag("0");
					rmsg.setContent("111111"); //回复文字消息


					session.callback(rmsg);
				}else{
//					msgpd = imgmsgService.findByKw(pd);
					if("2".equals(tmsg.getContent())){
						Msg4ImageText mit = new Msg4ImageText();
						mit.setFromUserName(toUserName);
						mit.setToUserName(fromUserName);
						mit.setCreateTime(createTime);
						if(null != "2"){
							//回复图文消息
							Data4Item d1 = new Data4Item("测试1", "测试描述", "http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg", "http://www.1b23.com");
							Data4Item d2 = new Data4Item("测试2", "测试描述", "http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg", "http://www.1b23.com");
							mit.addItem(d1);
							mit.addItem(d2);
							session.callback(mit);
						}

						//回复图文消息
						/*if(null != "22"){
							Data4Item d1 = new Data4Item(msgpd.getString("TITLE1"),msgpd.getString("DESCRIPTION1"),msgpd.getString("IMGURL1"),msgpd.getString("TOURL1")+"&FHWXID="+fromUserName);
							mit.addItem(d1);

							if(null != msgpd.getString("TITLE2") && null != msgpd.getString("IMGURL2") && !"".equals(msgpd.getString("TITLE2").trim()) && !"".equals(msgpd.getString("IMGURL2").trim())){
								Data4Item d2 = new Data4Item(msgpd.getString("TITLE2"),msgpd.getString("DESCRIPTION2"),msgpd.getString("IMGURL2"),msgpd.getString("TOURL2"));
								mit.addItem(d2);
							}
							if(null != msgpd.getString("TITLE3") && null != msgpd.getString("IMGURL3") && !"".equals(msgpd.getString("TITLE3").trim()) && !"".equals(msgpd.getString("IMGURL3").trim())){
								Data4Item d3 = new Data4Item(msgpd.getString("TITLE3"),msgpd.getString("DESCRIPTION3"),msgpd.getString("IMGURL3"),msgpd.getString("TOURL3"));
								mit.addItem(d3);
							}
							if(null != msgpd.getString("TITLE4") && null != msgpd.getString("IMGURL4") && !"".equals(msgpd.getString("TITLE4").trim()) && !"".equals(msgpd.getString("IMGURL4").trim())){
								Data4Item d4 = new Data4Item(msgpd.getString("TITLE4"),msgpd.getString("DESCRIPTION4"),msgpd.getString("IMGURL4"),msgpd.getString("TOURL4"));
								mit.addItem(d4);
							}
							if(null != msgpd.getString("TITLE5") && null != msgpd.getString("IMGURL5") && !"".equals(msgpd.getString("TITLE5").trim()) && !"".equals(msgpd.getString("IMGURL5").trim())){
								Data4Item d5 = new Data4Item(msgpd.getString("TITLE5"),msgpd.getString("DESCRIPTION5"),msgpd.getString("IMGURL5"),msgpd.getString("TOURL5"));
								mit.addItem(d5);
							}
							if(null != msgpd.getString("TITLE6") && null != msgpd.getString("IMGURL6") && !"".equals(msgpd.getString("TITLE6").trim()) && !"".equals(msgpd.getString("IMGURL6").trim())){
								Data4Item d6 = new Data4Item(msgpd.getString("TITLE6"),msgpd.getString("DESCRIPTION6"),msgpd.getString("IMGURL6"),msgpd.getString("TOURL6"));
								mit.addItem(d6);
							}
							if(null != msgpd.getString("TITLE7") && null != msgpd.getString("IMGURL7") && !"".equals(msgpd.getString("TITLE7").trim()) && !"".equals(msgpd.getString("IMGURL7").trim())){
								Data4Item d7 = new Data4Item(msgpd.getString("TITLE7"),msgpd.getString("DESCRIPTION7"),msgpd.getString("IMGURL7"),msgpd.getString("TOURL7"));
								mit.addItem(d7);
							}
							if(null != msgpd.getString("TITLE8") && null != msgpd.getString("IMGURL8") && !"".equals(msgpd.getString("TITLE8").trim()) && !"".equals(msgpd.getString("IMGURL8").trim())){
								Data4Item d8 = new Data4Item(msgpd.getString("TITLE8"),msgpd.getString("DESCRIPTION8"),msgpd.getString("IMGURL8"),msgpd.getString("TOURL8"));
								mit.addItem(d8);
							}
						}*/
						//mit.setFuncFlag("0");

					}else{
//						msgpd = commandService.findByKw(pd);
						if("1".equals(tmsg.getContent())){
							Runtime runtime = Runtime.getRuntime();
							runtime.exec("12");
						}else{
							Msg4Text rmsg = new Msg4Text();
							rmsg.setFromUserName(toUserName);
							rmsg.setToUserName(fromUserName);
							rmsg.setContent("无匹配结果");
							session.callback(rmsg);
						}
					}
				}
			} catch (Exception e1) {
				logBefore(logger, "匹配错误");
			}
		}

	});

	/*必须调用这两个方法   如果不调用close方法，将会出现响应数据串到其它Servlet中。*/
	session.process(is, os);	//处理微信消息
	session.close();			//关闭Session
}

//	 public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//         InputStream is = request.getInputStream();
//         OutputStream os = response.getOutputStream();
//		 IMessageHandler messageHandler = HandlerFactory.getMessageHandler();
//
//
//
//
//		 //处理输入消息，返回结果
//		 //ServletInputStream in = request.getInputStream();
//		 //String xml = messageHandler.invoke(in);
//		 //返回结果
//		 //response.getWriter().write(xml);
//		 //System.out.println(xml);
//
//         final DefaultSession session = DefaultSession.newInstance();
//         /*session.addOnHandleMessageListener(new HandleMessageAdapter(){
//
//        	 @Override
//             public void onTextMsg(Msg4Text msg) {
//                System.out.println("收到微信消息："+msg.getContent());
//                Process p;
//                //文字消息
//                if("1".equals(msg.getContent())){
//                     Msg4Text rmsg = new Msg4Text();
//                     rmsg.setFromUserName(msg.getToUserName());
//                     rmsg.setToUserName(msg.getFromUserName());
//                     //rmsg.setFuncFlag("0");
//                     rmsg.setContent("你好!");
//                     session.callback(rmsg);
//                    return;
//                 }else if("2".equals(msg.getContent())){
//                 //回复图文消息
//                 Data4Item d1 = new Data4Item("测试1", "测试描述", "http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg", "http://www.baidu.com");
//                 Data4Item d2 = new Data4Item("测试2", "测试描述", "http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg", "http://www.baidu.com");
//
//                 Msg4ImageText mit = new Msg4ImageText();
//
//                 mit.setFromUserName(msg.getToUserName());
//                 mit.setToUserName(msg.getFromUserName());
//                 mit.setCreateTime(msg.getCreateTime());
//
//                 mit.addItem(d1);
//                 mit.addItem(d2);
//                 //mit.setFuncFlag("0");
//                 session.callback(mit);
//                 }else if("打开QQ".equals(msg.getContent()) || "打开qq".equals(msg.getContent())){
//                	 Runtime runtime = Runtime.getRuntime();
//             		try {
//             			p = runtime.exec("D:/SOFT/QQ/QQ/Bin/qq");
//             		} catch (IOException e) {
//             			e.printStackTrace();
//             		}
//                 }else if("关闭QQ".equals(msg.getContent()) || "关闭qq".equals(msg.getContent())){
//                	 Runtime runtime = Runtime.getRuntime();
//                	 try {
//						//runtime.exec("taskkill /f /im calc.exe");
//                		 runtime.exec("taskkill /f /im qq.exe");
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//                 }else if("打开浏览器".equals(msg.getContent())){
//                	 Runtime runtime = Runtime.getRuntime();
//             		try {
//             			//p = runtime.exec("calc");
//             			p = runtime.exec("C:/Program Files/Internet Explorer/iexplore.exe");
//             		} catch (IOException e) {
//             			e.printStackTrace();
//             		}
//                 }else if("关闭浏览器".equals(msg.getContent())){
//                	 Runtime runtime = Runtime.getRuntime();
//                	 try {
//						//runtime.exec("taskkill /f /im calc.exe");
//                		 runtime.exec("taskkill /f /im iexplore.exe");
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//                 }else if("锁定计算机".equals(msg.getContent())){
//                	 Runtime runtime = Runtime.getRuntime();
//                	 try {
//						//runtime.exec("taskkill /f /im calc.exe");
//                		 runtime.exec("rundll32.exe user32.dll,LockWorkStation");
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//                 }else {
//					Msg4Text rmsg = new Msg4Text();
//					rmsg.setFromUserName(msg.getToUserName());
//					rmsg.setToUserName(msg.getFromUserName());
//					//rmsg.setFuncFlag("0");
//					rmsg.setContent("您输入的是："+msg.getContent());
//					session.callback(rmsg);
//					return;
//				}
//             }
//        });*/
//
//
///*必须调用这两个方法   如果不调用close方法，将会出现响应数据串到其它Servlet中。*/
//
//         session.process(is, os);	//处理微信消息
//         session.close();			//关闭Session
//     }

	//================================================获取关注列表==============================================================
	public final static String gz_url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=";
	//获取access_token
	@RequestMapping(value="/getGz")
	public void getGz(PrintWriter out) {
		logBefore(logger, "获取关注列表");
		try{
			String access_token = readTxtFile("d:/access_token.txt");

			System.out.println(access_token+"============");

			String requestUrl=gz_url.replace("ACCESS_TOKEN", access_token);

			System.out.println(requestUrl+"============");

			JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
			System.out.println(jsonObject);
			//System.out.println(jsonObject.getString("total")+"============");


PrintWriter pw;
			try {
				pw = new PrintWriter( new FileWriter( "d:/gz.txt" ) );
				pw.print(jsonObject.getString("total"));
		        pw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			out.write("success");
			out.close();

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

	//读取文件
	public String readTxtFile(String filePath) {
		try {
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
				new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					//System.out.println(lineTxt);
					return lineTxt;
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return "";
	}

	//================================================获取access_token==============================================================
	public final static String access_token_url="https://api.weixin.qq.com/cgi-bin/token?" +
			"grant_type=client_credential&appid=APPID&secret=APPSECRET";
	//获取access_token
	@RequestMapping(value="/getAt")
	public void getAt(PrintWriter out) {
		logBefore(logger, "获取access_token");
		try{
			String appid = "wxb7f6c9100ba0a6cc";
			String appsecret = "e8dcbbde25f54500058a6687324e3e3b";

			String requestUrl=access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
			JSONObject jsonObject=httpRequst(requestUrl, "GET", null);

			//System.out.println(jsonObject.getString("access_token")+"============");

			PrintWriter pw;
			try {
				pw = new PrintWriter( new FileWriter( "d:/access_token.txt" ) );
				pw.print(jsonObject.getString("access_token"));
		        pw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

	public JSONObject httpRequst(String requestUrl,String requetMethod,String outputStr){
		JSONObject jsonobject=null;
		StringBuffer buffer=new StringBuffer();
		try
		{
			//创建SSLContext对象，并使用我们指定的新人管理器初始化
			TrustManager[] tm={new MyX509TrustManager()};
			SSLContext sslcontext=SSLContext.getInstance("SSL","SunJSSE");
			sslcontext.init(null, tm, new java.security.SecureRandom());
			//从上述SSLContext对象中得到SSLSocktFactory对象
			SSLSocketFactory ssf=sslcontext.getSocketFactory();

			URL url=new URL(requestUrl);
			HttpsURLConnection httpUrlConn=(HttpsURLConnection)url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			//设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requetMethod);

			if("GET".equalsIgnoreCase(requetMethod))
				httpUrlConn.connect();

			//当有数据需要提交时
			if(null!=outputStr)
			{
			OutputStream outputStream=httpUrlConn.getOutputStream();
			//注意编码格式，防止中文乱码
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
			}

			//将返回的输入流转换成字符串
			InputStream inputStream=httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
			BufferedReader bufferedReader=new BufferedReader(inputStreamReader);


			String str=null;
			while((str = bufferedReader.readLine()) !=null)
			{
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			//释放资源
			inputStream.close();
			inputStream=null;
			httpUrlConn.disconnect();
			jsonobject=JSONObject.fromObject(buffer.toString());
		}
		catch (ConnectException ce) {
			// TODO: handle exception
		}
		catch (Exception e) {
		}
		return jsonobject;
	}
	//================================================获取access_token==============================================================
	//获取access_token
	@RequestMapping(value="/ceshi")
	public void ceshi(PrintWriter out) {
		logBefore(logger, "测试方法开始");
		try{
			String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
			AccessToken aa=WeixinUtil.getAccessToken("wxb7f6c9100ba0a6cc","e8dcbbde25f54500058a6687324e3e3b");
			System.out.println(aa.getToken());
			String URL = requestUrl.replace("ACCESS_TOKEN",aa.getToken());
			System.out.println(URL);
			String outputStr="touser=oV_bU1Q64Auw0xKwbbayI8xYQUPg&template_id=Mh40Kj6RQUNqvLv7sLo9akiqln6vjGYd5hFHLhbAFy8&";
			WeixinUtil.httpRequest(URL,"GET",outputStr);
			System.out.println(WeixinUtil.httpRequest(URL,"GET",outputStr));
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

	//================================================测试测试测试 获取菜单==============================================================
	public final static String gz_menu="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	//获取access_token
	@RequestMapping(value="/menu")
	public void getmenu(PrintWriter out) {
		logBefore(logger, "获取菜单");
		try{

			String access_token_url="https://api.weixin.qq.com/cgi-bin/token?" +
					"grant_type=client_credential&appid=wxb7f6c9100ba0a6cc&secret=e8dcbbde25f54500058a6687324e3e3b";
			System.out.println(access_token_url+"============");
			JSONObject jsonObject = httpRequst(access_token_url, "GET", null);//请求出 at

			String requestUrl=gz_menu.replace("ACCESS_TOKEN", jsonObject.getString("access_token").toString());

			System.out.println(requestUrl+"============");
			JSONObject jsonObject1 = httpRequst(requestUrl, "GET", null);
			//JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
			System.out.println(jsonObject1);
			//System.out.println(jsonObject.getString("total")+"============");

			out.write(jsonObject1.toString());
			out.close();

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

    //================================================获取access_token==============================================================
    class MyX509TrustManager implements X509TrustManager
    {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }
//================================================获取access_token==============================================================*/




    //================================================跳转测试==============================================================*/











	/**
	 * 登录界面绑定手机号
	 */
	@RequestMapping(value = "/weixin_login")
	public ModelAndView weixin_login() {
		logBefore(logger, "登录界面绑定手机号");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("/weixin_login");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 客户 提交 绑定 合同申请入口
	 */
	@RequestMapping(value = "/submit_con")
	@ResponseBody
	public PageData submit_con(HttpServletRequest request) {
		logBefore(logger, "客户 提交 绑定 合同申请入口");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);
			String s = pd.getString("con_list");
			String[] as = s.split(",");

			pd.put("OPEN_ID",map.get("OPEN_ID"));
			for (int i = 0; i < as.length; i++) {
				pd.put("CREATE_DATE",DateUtil.getTime());
				pd.put("ID",UuidUtil.get32UUID());
				pd.put("CONTRACT_ID",as[i]);
				System.out.println(pd);
				cUserService.save_reg_user(pd);
			}
			res.put("data", "");
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}
	/**
	 * 去合同页面
	 */
	@RequestMapping(value = "/weixin_con")
	public ModelAndView weixin_con() {
		logBefore(logger, "去公众号合同页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("con_list");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去合同详情
	 */
	@RequestMapping(value = "/con_info")
	public ModelAndView con_details() {
		logBefore(logger, "去合同详情");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
		    mv.addObject("ID",pd.get("id"));
			mv.setViewName("con_info");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去账单
	 */
	@RequestMapping(value = "/weixin_bill")
	public ModelAndView weixin_bill() {
		logBefore(logger, "去公众号账单页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			mv.setViewName("zhangdan/zhangdan");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}



	/**
	 * 获取账单数据
	 */
	@RequestMapping(value = "/weizinList")
	@ResponseBody
	public PageData weizinList(HttpServletRequest request) {

		PageData res = new PageData();
		PageData pd = this.getPageData();

		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);

			//pd.put("OPEN_ID",map.get("OPEN_ID"));
			List<PageData> list=billService.findByOPEN_IDAllBill(pd);
			res.put("list", list);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}

	/**
	 * 获取账单获取每月数据
	 */
	@RequestMapping(value = "/weizinDayList")
	@ResponseBody
	public PageData weizinDayList(HttpServletRequest request) {

		PageData res = new PageData();
		PageData pd = this.getPageData();

		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);

			//pd.put("OPEN_ID",map.get("OPEN_ID"));
			List<PageData> list=billService.findByOPEN_IDAllDayBill(pd);
			res.put("list", list);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}

	/**
	 * 获取单条账单
	 */
	@RequestMapping(value = "/findbyBill")
	@ResponseBody
	public PageData findbyBill(HttpServletRequest request) {

		PageData res = new PageData();
		PageData pd = this.getPageData();

		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);

			PageData bill =billService.findbyBill(pd);
			res.put("bill", bill);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}


	/**
	 * 获取物业信息
	 */
	@RequestMapping(value = "/findByOPEN_IDWUYEALLBill")
	@ResponseBody
	public PageData findByOPEN_IDWUYEALLBill(HttpServletRequest request) {

		PageData res = new PageData();
		PageData pd = this.getPageData();

		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);

			List<PageData> list =billService.findByOPEN_IDWUYEALLBill(pd);
			res.put("list", list);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}

	/**
	 * 获取物业详情
	 */
	@RequestMapping(value = "/findWUYWDetil")
	@ResponseBody
	public PageData findWUYWDetil(HttpServletRequest request) {

		PageData res = new PageData();
		PageData pd = new PageData(request);
		PageData bbb = this.getPageData();
		try {
			HttpSession session = request.getSession();
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);
			List<PageData>  data =billService.findWUYWDetil(pd);
			res.put("list", data);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}



	/**
	 * 去我的页面
	 */
	@RequestMapping(value = "/toIndex")
	public ModelAndView goMe(HttpServletRequest request, HttpServletResponse response) {
		logBefore(logger, "去我的页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			HttpSession session = request.getSession();
//			session.getAttribute(Const.SESSION_PORTAL_USER);
//			System.out.println(session.getAttribute(Const.SESSION_PORTAL_USER));;
			PageData map= (PageData) session.getAttribute(Const.SESSION_PORTAL_USER);
			map.get("OPEN_ID");
			// 查询openid是否已存在
			PageData userData= new PageData();
			userData.put("OPEN_ID",map.get("OPEN_ID"));
			PageData loginUser = cUserService.findByOpenId(userData);
			if (map==null){
				String url="weixin_login";
				mv.setViewName(url);
			}else {
				mv.addObject("msg", "edit");
				mv.addObject("pd", loginUser);
				mv.setViewName("weixin/my_list");
			}

		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去我的消息
	 */
	@RequestMapping(value = "/my_news")
	public ModelAndView my_news() {
		logBefore(logger, "去我的消息");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("my_news");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去我的物业
	 */
	@RequestMapping(value = "/my_property")
	public ModelAndView my_property() {
		logBefore(logger, "去我的物业");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.addObject("name", "edit");
			mv.setViewName("/wuye/wuyeList");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 去我的物业详情
	 */
	@RequestMapping(value = "/wuye_info")
	public ModelAndView wuye_info() {
		logBefore(logger, "去我的物业详情");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("/wuye/wuye");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}




	/**
     * 测试接口方法
     *//*
    @RequestMapping(value = "/ceshi")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "测试接口");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            res.put("data", "111");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
*/

	/**
	 * 去付款页面
	 */
	@RequestMapping(value = "/wuye_fukuan")
	public ModelAndView wuye_fukuan() {
		logBefore(logger, "去付款页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("/zhangdan/payment");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}



	/**
	 * 去物业
	 */
	@RequestMapping(value = "/wuyeList")
	public ModelAndView wuyeList() {
		logBefore(logger, "去物业页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("/wuye/wuyeList");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去物业详情
	 */
	@RequestMapping(value = "/wuyeDetil")
	public ModelAndView wuyeDetil() {
		logBefore(logger, "去物业详情");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("/wuye/wuye");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}
}


